﻿using AdminSystem.Application.Commands.lmgCommands;
using AdminSystem.Domain.Entities;
using AdminSystem.EntityFramworkCore;
using AdminSystem.Repositories.Interfaces;
using MediatR;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace AdminSystem.Application.CommandHandlers.lmgCommandHandlers
{
    public class lmgDelCommandHandler : IRequestHandler<lmgDelCommand, APIResult<object>>
    {
        private readonly IBaseRepositories<Images> imagesBase;
        private readonly IBaseRepositories<ImagesMiddle> imagesMiddleBase;
        public lmgDelCommandHandler(IBaseRepositories<Images> imagesBase, IBaseRepositories<ImagesMiddle> imagesMiddleBase)
        {
            this.imagesBase = imagesBase;
            this.imagesMiddleBase = imagesMiddleBase;
        }
        public async Task<APIResult<object>> Handle(lmgDelCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = ResultCode.删除成功;
            result.Message = ResultCode.删除成功.ToString();
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    Images images = await imagesBase.GetById(Convert.ToInt32(request.Id));
                    if (images == null)
                    {
                        result.Message = "图片不存在";
                        result.Codes = APIState.BadRequest;
                        return await Task.FromResult(result);
                    }
                    await imagesBase.DeleteAsync(images);

                    ImagesMiddle imagesMiddle = await imagesMiddleBase.GetByConditionAsync(x => x.ImgId == images.ImgId);

                    if (imagesMiddle != null)
                    {
                        await imagesMiddleBase.DeleteAsync(imagesMiddle);
                    }



                    //提交事务
                    scope.Complete();
                    return await Task.FromResult(result);
                }
                catch (Exception ex)
                {
                    result.Message = "删除失败";
                    result.Codes = APIState.BadRequest;
                    return await Task.FromResult(result);
                }
            }
           
        }
    }
}
